#include "pathfinder.h"

PathFinder::PathFinder(QImage mapMask, QObject *parent)
    : QThread(parent)
{
    pathMap = new PathMap(mapMask.width()/PIX_PER_POINT,mapMask.height()/PIX_PER_POINT);
    pather = new MicroPather(pathMap);

    pathCost = 0;

    qreal pointAverage = 0;

    // Calculate passable portions of the map
    for (int pointRow = 0; pointRow < pathMap->getWidth(); pointRow++)
    {
        for (int pointCol = 0; pointCol < pathMap->getHeight(); pointCol++)
        {
            for (int pixel = 0; pixel < PIX_PER_POINT*PIX_PER_POINT; pixel++)
            {
                QColor pixelColor = QColor::fromRgba(mapMask.pixel((pointRow*PIX_PER_POINT)+(pixel/PIX_PER_POINT),(pointCol*PIX_PER_POINT)+(pixel%PIX_PER_POINT)));
                if (pixelColor.alphaF() >= 0.5)
                    pointAverage++;
            }

            if (pointAverage/(PIX_PER_POINT*PIX_PER_POINT) < .4)
                pathMap->SetPointPassable(pointRow,pointCol,false);

            pointAverage = 0;
        }
    }
}

void PathFinder::run()
{
    exec();
}

void PathFinder::solvePath(QPoint start, QPoint finish, QObject *sender)
{
    pather->Solve(pathMap->XYToState(start.x(),start.y()),pathMap->XYToState(finish.x(),finish.y()),&tempPath,&pathCost);
    emit pathSolved(tempPath,sender);
}

PathMap * PathFinder::getPathMap()
{
    return pathMap;
}
